package com.training.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import com.base.BaseActivity;
import com.google.android.material.navigation.NavigationBarView;
import com.training.R;
import com.training.adapter.FragmentAdapter;
import com.training.bean.AppVersion;
import com.training.databinding.ActivityHomeBinding;
import com.training.fragment.HomeFragment;
import com.training.fragment.MineFragment;
import com.training.net.DataCenter;
import com.training.net.HttpResponse;
import com.training.net.NetCallback;
import com.training.util.ToastyUtil;

import java.util.ArrayList;

import retrofit2.Call;

public class HomeActivity extends BaseActivity<ActivityHomeBinding> {
    private MenuItem menuItem;
    private ArrayList<Fragment> fragments = new ArrayList<>();
    private HomeFragment homeFragment;
    private MineFragment mineFragment;

    @Override
    public ActivityHomeBinding binding() {
        return ActivityHomeBinding.inflate(getLayoutInflater());
    }

    @Override
    public void onCreated(Bundle savedInstanceState) {
        homeFragment = new HomeFragment();
        mineFragment = new MineFragment();
        fragments.add(homeFragment);
        fragments.add(mineFragment);
        mBinding.homeVp.setAdapter(new FragmentAdapter(this, fragments));
        mBinding.homeVp.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                menuItem = mBinding.homeBnv.getMenu().getItem(position);
                menuItem.setChecked(true);
            }
        });
        mBinding.homeBnv.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                menuItem = item;
                int itemId = item.getItemId();
                if (itemId == R.id.menu_home) {
                    mBinding.homeVp.setCurrentItem(0);

                } else {
                    mBinding.homeVp.setCurrentItem(1);
                }
                return true;
            }
        });
    }

    @Override
    public void loadData() {
        checkAppVersion();
    }

    @Override
    public void refreshUI() {

    }
    
    /**
     * 检查应用版本更新
     */
    private void checkAppVersion() {
            // 获取当前应用的版本信息
        PackageInfo packageInfo = null;
        try {
            packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
            int versionCode = packageInfo.versionCode;
            String versionName = packageInfo.versionName;
            dc.checkVersion(new NetCallback<HttpResponse<AppVersion>>() {
                @Override
                public void onError(int code, String message) {
                    ToastyUtil.showError(context, message, Toast.LENGTH_SHORT, true);
                }

                @Override
                public void onSuccess(HttpResponse<AppVersion> response) {
                    if (response.data.versionCode > versionCode){
                        showUpdateDialog(response.data);
                    }
                }

                @Override
                public void onFinally() {

                }
            });
        } catch (PackageManager.NameNotFoundException e) {
            throw new RuntimeException(e);
        }


    }
    
    /**
     * 显示版本更新对话框
     * @param version 新版本信息
     */
    private void showUpdateDialog(AppVersion version) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("发现新版本: " + version.versionName)
                .setMessage(version.description)
                .setCancelable(false) // 强制更新，不允许取消
                .setPositiveButton("立即更新", (dialog, which) -> {
                    // 启动浏览器下载新版本
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(version.filePath));
                    startActivity(intent);
                    // 关闭当前应用
                    finish();
                });
        AlertDialog dialog = builder.create();
        dialog.show();
    }
}
